package com.smart.community.property.controller;

import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.smart.community.commons.dto.property.PropertyCompanyQueryDTO;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.property.dto.PropertyCompanyAuditDTO;
import com.smart.community.property.service.IPropertyCompanyCommunityService;
import com.smart.community.property.service.IPropertyCompanyService;
import com.smart.community.property.service.DataScopeService;
import com.smart.community.property.vo.PropertyCompanyVO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 超级管理员专属Controller
 * 提供超级管理员专属的物业公司管理功能
 * @author Wu.Liang
 * @since 2025-06-29
 */
@Slf4j
@Tag(name = "超级管理员物业公司管理", description = "超级管理员专属的物业公司管理接口")
@RestController
@RequestMapping("/super-admin/property")
@RequiredArgsConstructor
@Validated
public class SuperAdminController {

    private final IPropertyCompanyService propertyCompanyService;
    private final IPropertyCompanyCommunityService propertyCompanyCommunityService;
    private final DataScopeService dataScopeService;

    @Operation(summary = "超级管理员查询物业公司列表", description = "超级管理员查询所有物业公司信息，无数据权限限制")
    @GetMapping("/companies")
    public Result<PageResult<PropertyCompanyVO>> getPropertyCompanyList(
            @Parameter(description = "查询条件") @ModelAttribute PropertyCompanyQueryDTO queryDTO,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        queryDTO.setCurrent(current);
        queryDTO.setSize(size);
        Result<PageResult<PropertyCompanyVO>> result = propertyCompanyService.getPropertyCompanyList(queryDTO);
        log.info("超级管理员查询物业公司列表成功，用户ID：{}", userId);
        return result;
    }

    @Operation(summary = "超级管理员查询物业公司社区", description = "超级管理员查询物业公司关联的社区列表，无数据权限限制")
    @GetMapping("/companies/{propertyCompanyId}/communities")
    public Result<List<com.smart.community.commons.entity.property.PropertyCompanyCommunity>> getPropertyCompanyCommunities(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        List<com.smart.community.commons.entity.property.PropertyCompanyCommunity> communities =
                propertyCompanyCommunityService.getPropertyCompanyCommunities(propertyCompanyId);
        log.info("超级管理员查询物业公司关联的社区成功，用户ID：{}，物业公司ID：{}，社区数量：{}", userId, propertyCompanyId, communities.size());
        return Result.success("查询成功", communities);
    }

    @Operation(summary = "超级管理员查询可分配社区", description = "超级管理员查询可以分配给物业公司的社区列表，无数据权限限制")
    @GetMapping("/companies/{propertyCompanyId}/available-communities")
    public Result<List<Object>> getAvailableCommunities(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String searchKeyword) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        List<Object> communities = propertyCompanyCommunityService.getAvailableCommunities(propertyCompanyId, searchKeyword);
        log.info("超级管理员查询可分配的社区成功，用户ID：{}，物业公司ID：{}，可分配社区数量：{}", userId, propertyCompanyId, communities.size());
        return Result.success(communities);
    }

    @Operation(summary = "超级管理员获取社区关联统计", description = "超级管理员获取物业公司的社区关联统计信息，无数据权限限制")
    @GetMapping("/companies/{propertyCompanyId}/community-stats")
    public Result<Object> getPropertyCompanyCommunityStats(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        Object stats = propertyCompanyCommunityService.getPropertyCompanyCommunityStats(propertyCompanyId);
        log.info("超级管理员获取物业公司社区关联统计成功，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);
        return Result.success("查询成功", stats);
    }

    @Operation(summary = "超级管理员分配社区", description = "超级管理员为物业公司分配社区，无数据权限限制")
    @PostMapping("/companies/{propertyCompanyId}/communities")
    public Result<String> assignCommunitiesToPropertyCompany(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @Parameter(description = "社区ID列表") @Valid @RequestBody List<Long> communityIds) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        Result<String> result = propertyCompanyCommunityService.assignCommunitiesToPropertyCompany(propertyCompanyId, communityIds);
        log.info("超级管理员分配社区成功，用户ID：{}，物业公司ID：{}，社区数量：{}", userId, propertyCompanyId, communityIds.size());
        return result;
    }

    @Operation(summary = "超级管理员批量移除社区关联", description = "超级管理员批量移除物业公司与社区的关联关系，无数据权限限制")
    @DeleteMapping("/companies/{propertyCompanyId}/communities")
    public Result<String> batchRemovePropertyCompanyCommunities(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId,
            @Parameter(description = "社区ID列表") @Valid @RequestBody List<Long> communityIds) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        Result<String> result = propertyCompanyCommunityService.batchRemovePropertyCompanyCommunities(propertyCompanyId, communityIds);
        log.info("超级管理员批量移除社区关联成功，用户ID：{}，物业公司ID：{}，社区数量：{}", userId, propertyCompanyId, communityIds.size());
        return result;
    }

    @Operation(summary = "超级管理员审核物业公司", description = "超级管理员审核物业公司申请，无数据权限限制")
    @PostMapping("/companies/{id}/audit")
    public Result<Void> auditPropertyCompany(
            @Parameter(description = "物业公司ID") @PathVariable @NotNull Long id,
            @Parameter(description = "审核信息") @Valid @RequestBody PropertyCompanyAuditDTO auditDTO) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        propertyCompanyService.auditPropertyCompany(id, auditDTO);
        log.info("超级管理员审核物业公司成功，用户ID：{}，物业公司ID：{}，审核状态：{}", userId, id, auditDTO.getAuditStatus());
        return Result.success();
    }

    @Operation(summary = "超级管理员批量审核物业公司", description = "超级管理员批量审核物业公司申请，无数据权限限制")
    @PostMapping("/companies/batch-audit")
    public Result<Object> batchAuditPropertyCompanies(
            @Parameter(description = "批量审核请求") @Valid @RequestBody List<BatchAuditRequest> auditRequests) throws Exception {
        Long userId = SecurityUtils.getCurrentUserId();
        if (!dataScopeService.isUserSuperAdmin(userId)) {
            return Result.fail("无权限访问超级管理员功能");
        }
        
        // 这里需要实现批量审核逻辑
        log.info("超级管理员批量审核物业公司，用户ID：{}，审核数量：{}", userId, auditRequests.size());
        return Result.success("批量审核成功");
    }

    /**
     * 批量审核请求内部类
     */
    public static class BatchAuditRequest {
        @NotNull(message = "物业公司ID不能为空")
        private Long propertyCompanyId;

        @NotNull(message = "审核状态不能为空")
        private Integer auditStatus;

        private String auditRemark;

        public Long getPropertyCompanyId() {
            return propertyCompanyId;
        }

        public void setPropertyCompanyId(Long propertyCompanyId) {
            this.propertyCompanyId = propertyCompanyId;
        }

        public Integer getAuditStatus() {
            return auditStatus;
        }

        public void setAuditStatus(Integer auditStatus) {
            this.auditStatus = auditStatus;
        }

        public String getAuditRemark() {
            return auditRemark;
        }

        public void setAuditRemark(String auditRemark) {
            this.auditRemark = auditRemark;
        }
    }
} 